package com.bringspring.system.base.controller;


import com.bringspring.common.filter.RepeatSubmit;
import com.bringspring.system.base.entity.ModuleEntity;
import com.bringspring.system.base.model.basemoduleoffen.BaseModuleOffenCrForm;
import com.bringspring.system.base.model.basemoduleoffen.BaseModuleOffenPagination;
import com.bringspring.system.base.service.BaseModuleOffenService;
import com.bringspring.system.base.service.ModuleService;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.mapper.UserMapper;
import com.bringspring.system.permission.service.UserService;
import io.swagger.annotations.Api;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.vo.PageListVO;
import com.bringspring.common.base.vo.PaginationVO;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.exception.DataException;
import org.springframework.transaction.annotation.Transactional;
import com.bringspring.common.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * pc常用菜单
 *
 * @版本： V1.0.0
 * @版权： 股份有限公司
 * @作者： 开发平台组
 * @日期： 2023-12-14
 */
@Slf4j
@RestController
@Api(tags = "pc常用菜单", value = "system")
@RequestMapping("/api/system/BaseModuleOffen")
public class BaseModuleOffenController {

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BaseModuleOffenService baseModuleOffenService;

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private CacheKeyUtil cacheKeyUtil;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 列表
     *
     * @param baseModuleOffenPagination
     * @return
     */
    @PostMapping("/getList")
    public ActionResult list(@RequestBody BaseModuleOffenPagination baseModuleOffenPagination) throws IOException {
        List<String> list = baseModuleOffenService.getList();
        List<ModuleEntity> moduleEntityList=new ArrayList<>();
        if (!list.isEmpty()) {
            for (String moduleId : list) {
                ModuleEntity info = moduleService.getInfo(moduleId);
                moduleEntityList.add(info);
            }
        }
        PageListVO vo = new PageListVO();
        vo.setList(moduleEntityList);
        PaginationVO page = JsonUtil.getJsonToBean(baseModuleOffenPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }


    /**
     * 创建
     *
     * @param baseModuleOffenCrForm
     * @return
     */
    @RepeatSubmit
    @PostMapping
    @Transactional
    public ActionResult create(@RequestBody @Valid BaseModuleOffenCrForm baseModuleOffenCrForm) throws DataException {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = userService.getInfo(userInfo.getUserId());
//        常用菜单不等于空，先清空，再添加
        if (Objects.nonNull(userEntity.getCommonMenu())){
            userEntity.setCommonMenu("");
        }

        String moduleIds="";
        for (String moduleId:baseModuleOffenCrForm.getModuleIdList()){
            moduleIds+=moduleId+",";
        }
        //判断是否要把最后一个逗号删除
        int count = 0; // 初始化计数器为0
        char ch=',';
        for (int i = 0; i < moduleIds.length(); i++) {
            if (moduleIds.charAt(i) == ch) {
                count++; // 如果当前字符与目标字符相等，则计数加1
            }
        }
//        选择大于1
        if (count>1){
            //把最后一个逗号删除
            String newModuleIds = moduleIds.substring(0, moduleIds.length() - 1);
            userEntity.setCommonMenu(newModuleIds);
        }

        userMapper.updateById(userEntity);
        return ActionResult.success("添加成功!");
    }



    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = userService.getInfo(userInfo.getUserId());
//        获取常用菜单集合
        List<String> list = baseModuleOffenService.getList();
        Iterator<String> iterator = list.iterator();
//        判断相同的moduleId值，删除
        for (String moduleId:list){
            if (moduleId.equals(id)){
                iterator.remove();
            }
        }
        String moduleIds="";
//        重新赋值
        for (int i=0;i<list.size();i++){
            moduleIds+= list.get(i) +",";
        }
        //判断是否要把最后一个逗号删除
        int count = 0; // 初始化计数器为0
        char ch=',';
        for (int i = 0; i < moduleIds.length(); i++) {
            if (moduleIds.charAt(i) == ch) {
                count++; // 如果当前字符与目标字符相等，则计数加1
            }
        }
//        选择大于1
        if (count>1){
            //把最后一个逗号删除
            String newModuleIds = moduleIds.substring(0, moduleIds.length() - 1);
            userEntity.setCommonMenu(newModuleIds);
        }

        // 是否从缓冲里面获取权限
        String cacheKey = cacheKeyUtil.getUserAuthorize() + userInfo.getUserId();
        redisUtil.remove(cacheKey);
//        赋值
        userMapper.updateById(userEntity);
        return ActionResult.success("取消成功");
    }


}

